<template>
  <div class="parent">
    <div class="back">
      <el-button @click="handleBack" class="icon-close"><el-icon><Back /></el-icon></el-button>
    </div>
    <el-scrollbar class="information-scroll">
      <div class="information">
        <div class="text-border1">
          <div class="text1"><span class="text-label">OrderId:</span>{{ resultData.id }}</div>
          <div class="text1"><span class="text-label">Name:</span>{{ resultData.nickName }}</div>
          <div class="text1"><span class="text-label">Dealer:</span>{{ resultData.dealer }}</div>
          <div class="text1"><span class="text-label">City:</span>{{ resultData.country?resultData.country :'' }}{{ resultData.city == 0?'':'.' + resultData.city }}</div>
        </div>
        <div class="text-border1">
          <div class="text2"><span class="text-label">Model:</span>{{ resultData.model }}</div>
          <div class="text2"><span class="text-label">Account:</span>{{ resultData.account }}</div>
        </div>
        <div class="text3">
          <span class="text-label">Fault Part:</span>{{ resultData.faultPart }}
        </div>
        <div class="text3">
          <span class="text-label">Reason:</span>
          <span class="text-label">Reason:</span>{{ resultData.reason }}
        </div>
        <div class="text-border2">
          <span class="text-label">Part Missing:</span>{{ resultData.partMissing }}
        </div>
        <div class="text-border3">
          <div class="text4"><span class="text-label">Part Damaged:</span>{{resultData.partDamaged}}</div>
          <div class="text4"><span class="text-label">No Response:</span>{{resultData.noResponse}}</div>
          <div class="text4"><span class="text-label">Description:</span>{{resultData.description}}</div>
        </div>
        <!-- 图片 -->
        <div class="text-border4">
          <span class="text-label">Image:</span>
          <div class="images-wrapper">
            <div v-for="(img,key) in images" :key="key" class="image-container">
                  <img 
                    v-if="!isBlobUrl(img) && !failedImages[key]"
                    :src="img" 
                    @click="openImageViewer(images,key)" 
                    class="image-thumbnail"
                    @error="handleImageError($event, key)"
                  >
                  <img 
                    v-else
                    src="../../assets/images/icon-damaged.png"
                    class="image-thumbnail"
                  >
            </div>     
          </div>
        </div>
        <!-- 订单状态 -->
        <div class="text-border1">
          <div class="text2">
            <span class="text-label">Order Status:</span>
            <el-radio-group v-model="orderStatus" @change="handleStatusChange">
              <el-radio :value="0" class="status0">Unhandled</el-radio>
              <el-radio :value="1" class="status1">Processing</el-radio>
              <el-radio :value="2" class="status2">Processed</el-radio>
            </el-radio-group>
          </div>
          <div class="text2"><span class="text-label">Create Time:</span>{{ resultData.createTime }}</div>
        </div>
        
        <!-- 留言 -->
        <p class="text-label" style="text-align: left;margin: 0 30px;">Message Information:</p>
        <div class="text-border5">
          <div v-for="(msg, index) in response" :key="index" class="border5-message">
            <div class="text5">
              <span class="text5-name">{{msg.fromName}}</span>
              <span class="text5-time">{{ msg.createTime }}</span>
            </div>
            <div class="text6">
              {{ msg.message }}
            </div>
          </div>
        </div>
        <div class="text-input">
          <el-input
            v-model="newMessage"
            placeholder="Please enter your message"
            class="message-input"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
          />
          <el-button
            type="primary"
            class="send-btn"
            :disabled="!newMessage.trim()"
            @click="sendMessage"
          >
            发送
          </el-button>
        </div>
      </div>
    </el-scrollbar>
    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="previewImages"
      :initial-index="previewIndex"
      @close="closeImageViewer"
    />
  </div>
</template>

<script setup>
  import { ref,onMounted,computed } from 'vue'
  import { ElMessage, ElImageViewer } from 'element-plus';
  import { useManageStore } from '../../store/manageStore';
  import { useLoading } from '../../utils/loading';
  import axios from 'axios';
  const BASE_URL = import.meta.env.VITE_API_URL;
  const manageStore = useManageStore();
  const { showLoading, hideLoading } = useLoading();
  const name = computed(() => manageStore.name)
  const props = defineProps({
    userData: {
      type: Object,
      default:null
    }
  })

  const usersData = ref(props.userData);
  const emit = defineEmits(['back', 'status-updated']);
  // 图片预览相关状态
  const showViewer = ref(false)
  const previewImages = ref([])
  const previewIndex = ref(0)
  // 记录加载失败的图片
  const failedImages = ref({})
  //订单状态
  const orderStatus = ref()
  //留言
  const newMessage = ref('');
  const response = ref([])
  //返回上一级
  function handleBack() {
    emit('back');
  }

  onMounted(async() => {
    try {
      showLoading('Loading data...');
      await getMessage()
      orderStatus.value = resultData.value.state || 0;
    } finally {
      hideLoading();
    }
  }) 

  // 处理后的用户数据
  const resultData = computed(() => {
    const data = {...usersData.value}
    // 解码account字段
    if (data.account) {
      try {
        data.account = atob(data.account)
      } catch (error) {
      }
    }
    return data
  })

  //修改订单状态
  const handleStatusChange = async() => {
    try {
      showLoading('Updating order status...');
      const res = await axios.post(`${BASE_URL}manage/updateAfterSale`,null,{
        params:{
          id:resultData.value.id,
          state:orderStatus.value
        }
      })
      if(res.data.code === 0){
        resultData.value.state = orderStatus.value
        emit('status-updated',{
          id:resultData.value.id,
          state:orderStatus.value
        })
      }
      
    } catch(error){
    } finally {
      hideLoading();
    }
  }
  //获取留言
  const getMessage = async() => {
    try {
      showLoading('Loading messages...');
      const res = await axios.get(`${BASE_URL}manage/responseNoteList`,{
        params:{
          id:resultData.value.id,
        }
      })
      response.value = res.data.data || [];
    } catch(error){
      ElMessage.error('Failed to obtain',error.msg);
    } finally {
      hideLoading();
    }
  }
  //发送留言
  const sendMessage = async() => {
    if (!newMessage.value.trim()) {
      ElMessage.warning('Please enter the message content');
      return;
    }
    try {
      showLoading('Sending message...');
      const res = await axios.post(`${BASE_URL}manage/addResponseNote`,{
        noteId:resultData.value.id,
        replyId:0,
        fromName:name.value,
        toName:resultData.value.nickName,
        message:newMessage.value
      })
      //获取到的留言添加到response列表
      // response.value.push({
      //   fromName:name.value,
      //   message:newMessage.value
      // })
      getMessage();
      //清空输入框
      newMessage.value = '';
      ElMessage.success('The message was sent successfully.');
    } catch(error){
      ElMessage.error('The sending failed',error.msg)
    } finally {
      hideLoading();
    }
  }
  
  //图片处理
  const images = computed(() => {
    if (!resultData.value.images) return []
    return resultData.value.images.split(',').filter(img => img.trim())
  })
  // 判断字段是否包含图片
  function isImageField(value) {
    if (typeof value !== 'string') return false
    // 支持更多图片格式和Base64图片
    return /\.(jpe?g|png|gif|webp|svg|bmp)(\?.*)?$/i.test(value) || /^data:image\/(jpe?g|png|gif|webp|svg|bmp)/i.test(value)
  }
  // 判断是否是blob URL
  const isBlobUrl = (url) => {
    return url.startsWith('blob:')
  }
  // 图片加载错误处理
  const handleImageError = (event, key) => {
    failedImages.value[key] = true
    event.target.style.display = 'none' // 隐藏损坏的图片
  }
  // 图片放大
  function openImageViewer(img, index= 0) {
    previewImages.value = Array.isArray(img) ? img : [img]
    previewIndex.value = index
    showViewer.value = true
  }
  // 关闭图片放大
  function closeImageViewer() {
    showViewer.value = false
  }
</script>

<style scoped>
  .parent {
    position: absolute;
    display: flex;
    margin-top: -80px;
    width: 97%;
    background-color:white;
    color: black;
    z-index: 11;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;
  }
  /* 返回按钮 */
  .back {
    position: relative;
    height: 70px;
    width: 100%;
  }
  .icon-close {
    position: absolute;
    right: 20px;
    top:5px;
    width: 80px;
    height: 40px;
    border: none !important;
    background-color: transparent !important;
    padding: 8px; /* 适当增加点击区域 */
    transition: all 0.3s ease; /* 添加过渡动画 */
  }
  .icon-close:hover {
    background-color: #f56c6c !important; /* Element UI 的 danger 红色 */
    border-radius: 4px; /* 添加圆角 */
  }
  .icon-close:hover .el-icon {
    color: white !important;
  }
  .el-icon {
    color: #606266; 
    font-size: 30px;
  }

  /* 屏幕滚动条 */
  .information-scroll {
    flex: 1;
  }
  .information {
    margin-bottom: 200px;
  }
  /* 数据栏样式 */
  .text-label {
    font-family: 'Franklin Gothic Medium';
    font-size: 20px;
    color: #557cb7;
    padding-right: 8px;
  }
  .text-border1 {
    display: flex;
    width: 1330px;
    overflow: hidden;
    box-sizing: border-box;
  }
  .text1 {
    width: 310px;
    height: 50px;
    text-align: left;
    border-radius: 12px;
    font-size: 18px;
    color: #464951;
    margin: 0 15px 23px 15px;
    padding: 0 20px;
    line-height: 50px;
    border: 1px solid #E2E8F0;
    box-sizing: border-box;
    white-space: nowrap;       /* 禁止换行 */
    overflow: hidden;          /* 隐藏溢出 */
  }
  .text2 {
    width: 650px;
    height: 50px;
    text-align: left;
    border-radius: 12px;
    font-size: 18px;
    color: #464951;
    margin: 0 15px 23px 15px;
    padding: 0 20px;
    line-height: 50px;
    border: 1px solid #E2E8F0;
    box-sizing: border-box; 
    white-space: nowrap;       /* 禁止换行 */
    overflow: hidden;          /* 隐藏溢出 */
  }
  .text3 {
    width: 1330px;
    min-height: 50px;
    text-align: left;
    border-radius: 12px;
    font-size: 18px;
    color: #464951;
    margin: 0 15px 23px 15px;
    padding: 0 20px;
    line-height: 50px;
    border: 1px solid #E2E8F0;
    box-sizing: border-box;
  }
  .text-border2 {
    width: 1330px;
    max-height: 110px;
    text-align: left;
    border-radius: 12px;
    font-size: 18px;
    color: #464951;
    margin: 0 15px 23px 15px;
    padding: 10px 20px;
    border: 1px solid #E2E8F0;
    box-sizing: border-box;
    white-space: pre-wrap; /* 保留空格和换行，允许自动换行 */
    overflow-wrap: break-word; /* 允许长单词或URL换行 */
  }
  .text-border3 {
    display: flex;
    width: 1330px;
    min-height: 100px;
    max-height: 220px;
  }
  .text4 {
    width: 413px;
    text-align: left;
    border-radius: 12px;
    font-size: 18px;
    color: #464951;
    margin: 0 15px 23px 15px;
    padding: 10px 20px;
    border: 1px solid #E2E8F0;
    box-sizing: border-box;
    white-space: pre-wrap; /* 保留空格和换行，允许自动换行 */
    overflow-wrap: break-word; /* 允许长单词或URL换行 */
  }
  /* 图片样式 */
  .text-border4 {
    display: flex;
    align-items: flex-start; /* 文字和图片顶部对齐 */
    width: 1330px;
    height: 220px;
    margin: 0 15px 23px 15px;
    padding: 20px;
    border-radius: 12px;
    border: 1px solid #E2E8F0;
    gap: 10px; 
    box-sizing: border-box;
  }
  .images-wrapper {
    display: flex;/* 图片横向排列 */
  }
  .image-container {
    width: 180px;
    height: 180px;
    margin-right: 55px;
  }
  .image-thumbnail {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border: 1px solid #eee;
    border-radius: 4px;
    transition: transform 0.2s;
    cursor: pointer; /* 鼠标悬停显示手型 */
  }
  .image-thumbnail:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  /* 订单状态样式 */
  :deep(.el-radio__label) {
    font-size: 18px; /* 调整字体大小 */
  }
  :deep(.el-radio__inner) {
    width: 20px; /* 调整圆圈大小 */
    height: 20px;
  }
  :deep(.el-radio) {
    margin: 0 15px;
  }
  :deep(.status0.is-checked .el-radio__inner) {
    background-color: rgb(129, 133, 129);
    border-color: rgb(129, 133, 129)
  }
  :deep(.status1.is-checked .el-radio__inner) {
    background-color: rgb(32, 146, 246);
    border-color: rgb(32, 146, 246);
  }
  :deep(.status2.is-checked .el-radio__inner) {
    background-color: rgb(0, 200, 50);
    border-color: rgb(0, 200, 50);
  }
  :deep(.status0.is-checked .el-radio__label) {
    color: rgb(129, 133, 129);
  }
  :deep(.status1.is-checked .el-radio__label) {
    color: rgb(32, 146, 246);
  }
  :deep(.status2.is-checked .el-radio__label) {
    color: rgb(0, 200, 50);
  }
  /* 留言框样式 */
  .text-border5 {
    width: 1330px;
    min-height: 200px;
    max-height: 600px;
    margin: 0 15px 5px 15px;
    border: 1px solid #E2E8F0;
    border-radius: 12px;
    box-sizing: border-box;
    overflow-y: auto;
    padding: 15px 20px;
    scroll-padding: 15px;
    background-color: rgba(250, 250, 250);
  }
  .border5-message {
    border-bottom: 1px dashed #E2E8F0;
    padding: 5px 20px 10px 20px;
    margin: 5px 0;
  }
  .text5 {
    height: 20px;
    margin-bottom: 10px;
    color: rgb(167, 171, 167);
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    box-sizing: border-box;
  }
  .text5-name{
    font-size: 18px;
  }
  .text5-time {
    font-size: 16px;
  }
  .text6 {
    text-align: left;
    font-size: 17px;
    line-height: 1.5;
    text-indent: 2em;
    padding-right: 150px;
    box-sizing: border-box;
  }


  /* 输入区域 */
  .text-input {
    display: flex;
    width: 1330px;
    padding: 8px 16px;
    flex-shrink: 0;
  }
  .message-input {
    flex: 1;
    margin-right: 8px;
  }
  .message-input :deep(.el-textarea__inner) {
    resize: none; /* 禁用手动调整大小 */
    line-height: 1.5;
    font-size: 17px;
  }
  .send-btn {
    width: 80px;
    align-self: flex-end;
    margin-bottom: 4px;
  }
</style>